import sys
import re

import markdown  # pip3 install markdown


def replace_tex(content):
    """处理 tex 公式（行内、行间）
    """
    interline_tag = '\n<img src="https://www.zhihu.com/equation?tex={}" alt="{}\\\\" class="ee_img tr_noresize" eeimg="1">\n'
    interline_pattern = '\$\$([\s\S]*?)\$\$'
    inline_tag = '<img src="https://www.zhihu.com/equation?tex={}" alt="{}" class="ee_img tr_noresize" eeimg="1">'
    inline_pattern = '\$([\s\S]*?)\$'
    magic_tag = "🐶some🐒magic🚚tag⚽️"   # 保护 interline tex block 里内嵌的 $inline$ 用的特殊字符串

    def dashrepl(matchobj, tag):
        formular = matchobj.group(1)

        # protect nested $inline$ in an interline tex block
        formular = formular.replace("$", magic_tag)

        formular = formular.replace("\n", " ")
        return tag.format(formular, formular)

    content = re.sub(interline_pattern,
                     lambda mo: dashrepl(mo, interline_tag),
                     content)
    content = re.sub(inline_pattern,
                     lambda mo: dashrepl(mo, inline_tag),
                     content)

    content = content.replace(magic_tag, "$")    # 还原 $inline$

    return content


def replace_table(content):
    """处理表格

        bug: 表格内的行内公式不渲染，显示为TeX源码
    """
    # refer: https://regex101.com/library/V5BI9q
    table_pattern = '(\n\n(\|.+\|\n)+\n)'
    table_tag = '<table data-draft-node="block" data-draft-type="table" data-size="normal" data-row-style="normal">'

    def md_table_to_html(matchobj):
        table_md = matchobj.group(1)
        table_html = markdown.markdown(
            table_md,
            extensions=['markdown.extensions.tables']
        ).replace("<table>", table_tag)\
            .replace("\n", "")\
            .replace("<thead>", "<tbody>")\
            .replace("</thead><tbody>", "")
        table_html = f"\n\n{table_html}\n\n"
        return table_html

    content = re.sub(table_pattern, lambda mo: md_table_to_html(mo), content)
    return content


handlers = [replace_tex, replace_table]


def usage():
    print("usage: mdzh path/to/xxx.md")
    print("mdzh is a MarkDown preprocesser for ZhiHu")
    print("  input: xxx.md\n  output: xxx.zhihu.md (然后去知乎->写文章->文档导入，选择这个文件)")


def main():
    assert len(sys.argv) > 1, "Error: need filename as a argument"

    filename = sys.argv[1]
    assert filename.endswith(".md"), "Error: expect a `.md` input file"

    outfile = re.sub('\.md$', '.zhihu.md', filename)

    with open(filename, 'r') as f:
        content = f.read()

    for handler in handlers:
        content = handler(content)

    with open(outfile, 'w') as f:
        f.write(content)

    print(outfile)


if __name__ == '__main__':
    try:
        main()
    except AssertionError as e:
        print(e)
        usage()
